package com.oraycn.esbasic.listeners;

import android.app.Activity;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager; 

public class FloatingOnTouchListener implements View.OnTouchListener {
    private int x;
    private int y;
    private boolean isDowning=false;
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private Activity activity;
    public FloatingOnTouchListener(Activity activity){
        windowManager=(WindowManager) activity.getSystemService(activity.WINDOW_SERVICE);
        layoutParams=new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                x = (int) event.getRawX();
                y = (int) event.getRawY();
                layoutParams.x=x;
                layoutParams.y=y;
                isDowning=true;
                windowManager.addView(view,layoutParams);
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        if(!isDowning){
//                            Log.d("btn listener:", "btn is clicked!");
//                            backActivity();
//                        }
//                        //防止handler引起的内存泄漏
//                        handler.removeCallbacksAndMessages(null);
//                    }
//                },300);

                break;
            case MotionEvent.ACTION_MOVE:
                int nowX = (int) event.getRawX();
                int nowY = (int) event.getRawY();
                int movedX = nowX - x;
                int movedY = nowY - y;
                x = nowX;
                y = nowY;
                layoutParams.x = layoutParams.x + movedX;
                layoutParams.y = layoutParams.y + movedY;
                windowManager.updateViewLayout(view, layoutParams);
                break;
            case MotionEvent.ACTION_UP:
                isDowning=false;
                windowManager.removeView(view);
            default:
                break;
        }
        return true;
    }
}
